#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h> // 注意：在某些系统上可能是<netinet/in.h>的一部分或别名
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
 
#define PORT 8080
#define BUFFER_SIZE 1024
 
int main() {
    int sockfd;
    struct sockaddr_in serverAddr, clientAddr;
    socklen_t addrLen = sizeof(clientAddr);
    char buffer[BUFFER_SIZE];
 
    // 创建 UDP 套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
 
    // 绑定套接字到指定端口
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(8888);
 
    if (bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        perror("bind failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    int broadcastEnable = 1;
    //
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &broadcastEnable, sizeof(broadcastEnable)) < 0) {
        perror("setsockopt(SO_BROADCAST) failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

 
    // 接收广播消息（注意：这里应该是阻塞等待，直到收到消息）
    ssize_t numBytes = recvfrom(sockfd, buffer, BUFFER_SIZE - 1, 0, (struct sockaddr*)&clientAddr, &addrLen);
    if (numBytes < 0) {
        perror("recvfrom failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    // 确保字符串以null字符结尾
    buffer[numBytes] = '\0';
    // 使用printf输出接收到的消息
    printf("Received broadcast message: %s\n", buffer);
 
    // 关闭套接字
    close(sockfd);
 
    return 0;
}